package com.xygood.netdisk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.baidu.netdisk.BaiduClient;
import com.baidu.netdisk.BaiduListFileInfo;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends ActionBarActivity {
	private static final String TAG = "MainActivity";
	private static final String PREF_NAME = "LoginPref";
	private static final String PREF_BAIDU_COOKIE = "baidu_cookie";
	
	private final Map<String, String> mYundataMap = new HashMap<String, String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			rootView.findViewById(R.id.login).setOnClickListener(
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							getActivity().startActivity(
									new Intent(getActivity(),
											LoginActivity.class));

						}
					});

			rootView.findViewById(R.id.list).setOnClickListener(
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							SharedPreferences settings = getActivity()
									.getSharedPreferences(PREF_NAME, 0);
							final String cookie = settings.getString(
									PREF_BAIDU_COOKIE, "");
							if (!TextUtils.isEmpty(cookie)) {

								((MainActivity) getActivity()).getCookies(cookie);

							}
						}
					});

			return rootView;
		}
	}
	
	void getCookies (final String cookie) {
		new Thread() {
			public void run() {
				
				BaiduClient client = new BaiduClient(cookie);
				List<BaiduListFileInfo> list = client.getFileList("/来自：NX507J/DCIM/Camera");
				
				for (BaiduListFileInfo info : list) {
					Log.d(TAG, "filename = " + info.getFileName());
				}
				
				
				Log.d(TAG, "sign = " + client.getSign());
				
				client.getDownloadUrl(list.get(3).getFsId());
				
				/*
			URL url = null;
			try {
				url = new URL(
						"http://pan.baidu.com/disk/home?adapt=pc");
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}				
			
			HttpURLConnection conn = null;
			try {
				conn = (HttpURLConnection) url
						.openConnection();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			conn.addRequestProperty("Cookie",
					cookie);
			
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(
						new InputStreamReader(conn
								.getInputStream()));
				String s = null;
				
				String result = "";
				while ((s = reader.readLine()) != null ) {
					result +=s;
					//Log.d(TAG, "reader res = " + s);
				}
				
				
				String regex = "\\byunData\\.(\\w+)\\s*=\\s*\"([^\"]+)\"";
				Pattern pttern = Pattern.compile(regex);
				Matcher matcher = pttern.matcher(result);
				while(matcher.find()) {
					Log.d(TAG, "reader key = " + matcher.group(1) + " = " + matcher.group(2));
					
					mYundataMap.put(matcher.group(1), matcher.group(2));
				}
				
				String bdsToken = mYundataMap.get("MYBDSTOKEN");
				if (!TextUtils.isEmpty(bdsToken)) {
					getList(bdsToken, cookie);
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			*/
			

			 
			}}.start();
		
	}
	String getToken(final String cookie) {
		new Thread() {
			public void run() {

				try {

					/*URL url = new URL(
							"https://passport.baidu.com/v2/api/?getapi&tpl=mn&apiver=v3&class=login");*/
	
					URL url = new URL(
							"https://passport.baidu.com/v2/api/?getapi&tpl=netdisk&class=login&logintype=basicLogin");				
					
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.addRequestProperty("Cookie",
							cookie);

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(conn
									.getInputStream()));
					
					StringBuilder builder = new StringBuilder();

					String res;
					while((res = reader.readLine()) != null) {
						
						builder.append(res);
					}
					reader.close();
					int start =builder.indexOf("login_token='")+13;
					int end = builder.indexOf("'", start);
					
					res = builder.substring(start, end);
							Log.d(TAG, "builder = " + builder.toString());
							Log.d(TAG, "res = " + res);
							//getList(res);
					
							/*JSONTokener jsonParser = new JSONTokener(builder.toString());  
					try {
						JSONObject info = (JSONObject)jsonParser.nextValue();
						int err = info.getJSONObject("errInfo").getInt("no");
						if (err == 0) {
							final String token = info.getJSONObject("data").getString("token");
							Log.d(TAG, "token = " + token);
							getList(token);
							runOnUiThread(
									new Runnable() {

										@Override
										public void run() {
											Toast.makeText(
													MainActivity.this,
													token,
													Toast.LENGTH_SHORT)
													.show();

										}
									});
							
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}*/
	

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
		
		
		return null;
		
	}
	
	
	
	void getList(String token, String cookie) {
		 
		StringBuilder builder = new StringBuilder("http://pan.baidu.com/api/list?channel=chunlei&clienttype=0&app_id=250528&web=1&showempty=0&num=100&page=1");
		try {
			builder.append("&dir=" + URLEncoder.encode("/", "utf-8"));
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		}
		builder.append("&order=time");
		builder.append("&desc=1");
		builder.append("&bdstoken="+token);
		builder.append("&_="+System.currentTimeMillis());
		Log.d(TAG, "list url = " + builder.toString());
		
		try {
			HttpURLConnection conn = (HttpURLConnection) (new URL(builder.toString()).openConnection());
			
			conn.addRequestProperty("Cookie",cookie);
			
			conn.addRequestProperty("Referer","http://pan.baidu.com/disk/home?adapt=pc");
			conn.addRequestProperty("X-Requested-With","XMLHttpRequest");
			
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(conn
							.getInputStream()));
			
			final String res = reader.readLine();
			Log.d(TAG, "list res = " + res);
			
			
			runOnUiThread(
					new Runnable() {

						@Override
						public void run() {
							Toast.makeText(
									MainActivity.this,
									res,
									Toast.LENGTH_SHORT)
									.show();

						}
					});
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	

}
